const service = require('../../services/note-service');
const messages = require('../../common/messages');
const UiHelper = require('../../common/ui-helper');
const timeHelper = require('../../common/time-helper');

const uiHelper = new UiHelper();

Page({
  data: {
    item: {
      note: {
        id: null,
        ownerId: '',
        title: '',
        summary: '',
        createdAt: '2025-04-05T10:08:06.000+00:00',
      },
      owner: {
        id: null,
        name: '',
        avatar: '',
      },
    },
    ui: {
      createdAtUi: '',
    },
  },

  emptyData() {
    return {
      item: {
        note: {
          id: null,
          ownerId: '',
          title: '',
          summary: '',
          createdAt: '2025-04-05T10:08:06.000+00:00',
        },
        owner: {
          id: null,
          name: '',
          avatar: '',
        },
      },
      ui: {
        createdAtUi: '',
      },
    };
  },

  onLoad(options) {
    if (options && options.id !== null && options.id > 0) {
      this.initPageById(options.id);
    } else {
      this.resetPage();
    }
  },
  resetPage() {
    this.setData(this.emptyData());
  },
  initPageById(id) {
    service
      .queryById(id)
      .then((res) => {
        const item = res.data;
        this.setData({
          item: item,
          ui: {
            createdAtUi: timeHelper.timestampToDateTime(item.note.createdAt),
          },
        });
        const content = item.note.content === null ? '' : item.note.content;
        uiHelper.writeContent('content-editor', content).catch(messages.showError);
      })
      .catch(messages.showError);
  },

  onCancel: function () {
    wx.navigateBack();
  },
});
